import React, { Component } from 'react';
import styles from './index.less';

export default class Bubble extends Component {
  componentDidMount() {
    this.oDiv = document.getElementById('bubbleContent');
    this.aA = document.getElementsByName('bubbleItem');
    for (let i = 0; i < this.aA.length; i++) {
      this.aA[i].pause = 1;
      this.aA[i].time = null;
      this.initialize(this.aA[i]);
      this.aA[i].onmouseover = function() {
        this.pause = 0;
      };
      this.aA[i].onmouseout = function() {
        this.pause = 1;
      };
    }
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    this.timer = setInterval(this.starMove, 50);
  }

  componentWillUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }

  starMove = () => {
    for (let i = 0; i < this.aA.length; i++) {
      if (this.aA[i].pause) {
        this.doMove(this.aA[i]);
      }
    }
  };

  doMove = obj => {
    if (obj.offsetTop <= -obj.offsetHeight) {
      obj.style.top = `${this.oDiv.offsetHeight}px`;
      this.initialize(obj);
    } else {
      obj.style.top = `${obj.offsetTop - obj.ispeed}px`;
    }
  };

  initialize = obj => {
    const iLeft = parseInt(Math.random() * this.oDiv.offsetWidth, 10);

    const scale = Math.random() + 1;
    const iTimer = parseInt(Math.random() * 1500, 10);
    obj.pause = 1;

    obj.style.fontSize = `${12 * scale}px`;
    obj.style.top = `${parseInt(Math.random() * 700, 10) + 1}px`;

    if (iLeft - obj.offsetWidth > 0) {
      obj.style.left = `${iLeft - obj.offsetWidth}px`;
    } else {
      obj.style.left = `${iLeft}px`;
    }
    clearTimeout(obj.time);
    obj.time = setTimeout(function() {
      obj.pause = 1;
    }, iTimer);
    obj.ispeed = Math.ceil(Math.random() * 4) + 1;
  };

  render() {
    return (
      <div id="bubbleContent" className={styles.bubbleContent}>
        <div name="bubbleItem">1</div>
        <div name="bubbleItem">2</div>
        <div name="bubbleItem">3</div>
        <div name="bubbleItem">4</div>
        <div name="bubbleItem">5</div>
        <div name="bubbleItem">6</div>
        <div name="bubbleItem">7</div>
        <div name="bubbleItem">8</div>
        <div name="bubbleItem">9</div>
        <div name="bubbleItem">10</div>
      </div>
    );
  }
}
